package com.jeecg.school.controller;
import com.jeecg.school.entity.LoanApplyEntity;
import com.jeecg.school.entity.StudentEntity;
import com.jeecg.school.service.LoanApplyServiceI;
import com.jeecg.school.service.StudentServiceI;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.hibernate.qbc.PagerUtil;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;


/**   
 * @Title: Controller  
 * @Description: 贷款申请
 * @author onlineGenerator
 * @date 2020-02-22 09:58:03
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/loanApplyController")
public class LoanApplyController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(LoanApplyController.class);

	@Autowired
	private LoanApplyServiceI loanApplyService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private StudentServiceI studentService;


	/**
	 * 贷款申请列表 管理员页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		String loginSign = ResourceUtil.getSessionLoginSign();
		switch(loginSign) {
		case "1": 
			return new ModelAndView("school/loanApplyList-stu");
		case "2": 
			request.setAttribute("isShen", 0);
			return new ModelAndView("school/loanApplyList-teacher");
		}
		return new ModelAndView("school/loanApplyList");
	}
	
	/**
	 * 贷款申请列表 管理员页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "dealList")
	public ModelAndView deaLlist(HttpServletRequest request) {
		request.setAttribute("isShen", 1);
		return new ModelAndView("school/loanApplyList-teacher");
	}
	
	/**
	 * 贷款申请列表 管理员页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "doneList")
	public ModelAndView doneLlist(HttpServletRequest request) {
		request.setAttribute("isShen", 2);
		return new ModelAndView("school/loanApplyList-teacher");
	}
	
	/**
	 * 贷款申请列表 教师审批页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goDeal")
	public ModelAndView goDeal(String loanApplyId,HttpServletRequest request) {
		
		if (StringUtil.isNotEmpty(loanApplyId)) {
			LoanApplyEntity loanApply = loanApplyService.getEntity(LoanApplyEntity.class, loanApplyId);
			request.setAttribute("loanApplyPage", loanApply);
			if(StringUtil.isNotEmpty(loanApply.getApplyId())) {
				StudentEntity student = studentService.getEntity(StudentEntity.class, loanApply.getApplyId());
				request.setAttribute("studentPage", student);
			}
		}
		return new ModelAndView("school/loanApply-deal"); 
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(LoanApplyEntity loanApply,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,
			int isShen) {
		CriteriaQuery cq = new CriteriaQuery(LoanApplyEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, loanApply, request.getParameterMap());
		try{
		//自定义追加查询条件
			String sql1=" SELECT g.id,loan_status loanStatus, apply_year applyYear,apply_detali applyDetali,"
					+ "deal_date dealDate, deal_detail dealDetail,apply_date applyDate,"
					+ "repaly_name repalyName,loan_money loanMoney,loan_year loanYear,"
					+ "s.stu_name,t.teacher_name "
					+ " FROM loan_apply g left join teacher t on g.deal_id = t.id "
					+ " left join student s on s.id =apply_id  where 1=1 ";
	        String sql2=" SELECT count(1) FROM loan_apply g where 1=1 ";
	        
	        String loginSign = ResourceUtil.getSessionLoginSign();
	        TSUser user = ResourceUtil.getSessionUser();
			switch(loginSign) {
			case "1": 
				sql1+=" and g.apply_id ='"+user.getId()+"'";
	            sql2+=" and g.apply_id ='"+user.getId()+"'";
	            break;
			case "2": 
				sql1+=" and EXISTS(SELECT 1 FROM student s where s.id = g.apply_id and EXISTS("
						+ "select 1 from grade a where a.id = s.grad_id and a.teacher_id =" 
							+user.getId()+" ) )";
	            sql2+=" and EXISTS(SELECT 1 FROM student s where s.id = g.apply_id and EXISTS("
						+ "select 1 from grade a where a.id = s.grad_id and a.teacher_id =" 
						+user.getId()+" ) )";
	            break;
			}

			switch(isShen) {
			case 1: 
				sql1+=" and g.loan_status =1 ";
	            sql2+=" and g.loan_status =1 ";
	            break;
			case 2: 
				sql1+=" and g.loan_status in(2,3,4) ";
	            sql2+=" and g.loan_status in(2,3,4) ";
	            break;
			}
			
	        String applyYear = request.getParameter("applyYear");
	        if (StringUtil.isNotEmpty(applyYear)) {
	            sql1+=" and apply_year ="+applyYear;
	            sql2+=" and apply_year ="+applyYear;
	        }
	        String loanStatus = request.getParameter("loanStatus");
	        if (StringUtil.isNotEmpty(loanStatus)) {
	            sql1+=" and loan_status ="+loanStatus;
	            sql2+=" and loan_status ="+loanStatus;
	        }
	        String applyId = request.getParameter("applyId");
	        if (StringUtil.isNotEmpty(applyId)) {
	            sql1+=" and s.stu_name like'%"+applyId+"%'";
	            sql2+=" and s.stu_name like'%"+applyId+"%'";
	        }
	        String id = request.getParameter("id");
	        if (StringUtil.isNotEmpty(id)) {
	            sql1+=" and g.id like'%"+id+"%'";
	            sql2+=" and g.id like'%"+id+"%'";
	        }
	        sql1+=" order by g.id desc";

	        /*获取总数，用于分页使用*/
	        long countMwo = systemService.getCountForJdbc(sql2);
	        /*转换为 int 整形*/
	        int allCounts = (int)countMwo;

	        int pageSize = cq.getPageSize();/*每页显示数*/
	        int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),pageSize);// 当前页
	        
	        /*获取数据列表，参数一：查询的sql、参数二三：当前页码、数据总数*/
	        List<Map<String, Object>> listMwo=systemService.findForJdbc(sql1, curPageNO, pageSize);

	        cq.getDataGrid().setResults(listMwo);

	        cq.getDataGrid().setTotal(allCounts);
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		//this.loanApplyService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除贷款申请
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(LoanApplyEntity loanApply, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		loanApply = systemService.getEntity(LoanApplyEntity.class, loanApply.getId());
		message = "贷款申请删除成功";
		try{
			loanApplyService.delete(loanApply);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "贷款申请删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除贷款申请
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "贷款申请删除成功";
		try{
			for(String id:ids.split(",")){
				LoanApplyEntity loanApply = systemService.getEntity(LoanApplyEntity.class, 
				id
				);
				loanApplyService.delete(loanApply);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "贷款申请删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加贷款申请
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(LoanApplyEntity loanApply, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "贷款申请添加成功";
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
		loanApply.setLoanStatus(1);
		loanApply.setApplyDate(new Date());
		try{
			loanApplyService.save(loanApply);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "贷款申请添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新贷款申请
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(LoanApplyEntity loanApply, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "贷款申请更新成功";
		LoanApplyEntity t = loanApplyService.get(LoanApplyEntity.class, loanApply.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(loanApply, t);
			loanApplyService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "贷款申请更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 贷款审批
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doDeal")
	@ResponseBody
	public AjaxJson doDeal(LoanApplyEntity loanApply, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "贷款审批成功";
		switch(loanApply.getDealResult()) {
		case 1:
			loanApply.setLoanStatus(2);
			break;
		case 2:
			loanApply.setLoanStatus(3);
			break;
		case 3:
			loanApply.setLoanStatus(4);
			break;
		}
		loanApply.setDealDate(new Date());
		String loginSign = ResourceUtil.getSessionLoginSign();
		if(loginSign.equals("2")) {
			TSUser user = ResourceUtil.getSessionUser();
			loanApply.setDealId(Integer.parseInt(user.getId()));
		}
		LoanApplyEntity t = loanApplyService.get(LoanApplyEntity.class, loanApply.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(loanApply, t);
			loanApplyService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "贷款审批失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 贷款申请新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(LoanApplyEntity loanApply, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(loanApply.getId())) {
			loanApply = loanApplyService.getEntity(LoanApplyEntity.class, loanApply.getId());
			req.setAttribute("loanApplyPage", loanApply);
		}
		String loginSign = ResourceUtil.getSessionLoginSign();
		if(loginSign.equals("1")) {
			TSUser user = ResourceUtil.getSessionUser();
			StudentEntity student = studentService.getEntity(StudentEntity.class, user.getId());
			req.setAttribute("studentPage", student);
		}
		return new ModelAndView("school/loanApply-add");
	}
	/**
	 * 贷款申请编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(LoanApplyEntity loanApply, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(loanApply.getId())) {
			loanApply = loanApplyService.getEntity(LoanApplyEntity.class, loanApply.getId());
			req.setAttribute("loanApplyPage", loanApply);
			StudentEntity student = studentService.getEntity(StudentEntity.class, loanApply.getApplyId());
			req.setAttribute("studentPage", student);
		}
		return new ModelAndView("school/loanApply-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","loanApplyController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(LoanApplyEntity loanApply,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(LoanApplyEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, loanApply, request.getParameterMap());
		List<LoanApplyEntity> loanApplys = this.loanApplyService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"贷款申请");
		modelMap.put(NormalExcelConstants.CLASS,LoanApplyEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("贷款申请列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,loanApplys);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(LoanApplyEntity loanApply,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"贷款申请");
    	modelMap.put(NormalExcelConstants.CLASS,LoanApplyEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("贷款申请列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<LoanApplyEntity> listLoanApplyEntitys = ExcelImportUtil.importExcel(file.getInputStream(),LoanApplyEntity.class,params);
				for (LoanApplyEntity loanApply : listLoanApplyEntitys) {
					loanApplyService.save(loanApply);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
}
